<template>
  <div>
    <head-top></head-top>
    <div class="box">
      <h3>添加学生信息</h3>
      <el-form :model="student" status-icon ref="student" label-width="100px" class="demo-student" :disabled="elForm">
        <el-form-item label="学号" prop="id">
          <el-input @blur="checkStudentId()" class="i1" type="text" autocomplete="off" v-model="student.id"
            :disabled="idFrom" />
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input class="i1" type="text" autocomplete="off" v-model="student.name"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-select class="q1" v-model="student.sex" placeholder="请选择性别">
            <el-option :value="0" label="男" />
            <el-option :value="1" label="女" />
          </el-select>
        </el-form-item>

        <el-form-item label="年龄" prop="age">
          <el-input class="i1" v-model.number="student.age"></el-input>
        </el-form-item>

        <el-form-item label="毕业学校" prop="school">
          <el-input class="i2" type="text" autocomplete="off" v-model="student.school"></el-input>
        </el-form-item>
        <el-form-item label="专业" prop="major">
          <el-input class="i2" type="text" autocomplete="off" v-model="student.specialty"></el-input>
        </el-form-item>
        <el-form-item label="现住址" prop="currentAddress">
          <el-input class="i3" type="text" autocomplete="off" v-model="student.currentaddress"></el-input>
        </el-form-item>
        <el-form-item label="籍贯" prop="address">
          <el-input class="i3" type="text" autocomplete="off" v-model="student.nativeplace"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input class="i2" type="text" autocomplete="off" v-model="student.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input class="i1" type="text" autocomplete="off" v-model="student.phone"></el-input>
        </el-form-item>
        <!-- 员工头像 -->
        <el-form-item label="照片">
          <el-upload class="avatar-uploader" action="http://114.116.52.2:8008/teaching/oss/file/upload"
            :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
            <img v-if="imgUrl" :src="imgUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>

        <el-form-item class="buton">
          <el-button type="primary" @click="saveOrUpdate()">保存</el-button>
          <el-button @click="resetForm('student')" :disabled="resetBtn">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>
  
<script>
import headTop from '../../components/headTop.vue';
import axios from 'axios';
export default {
  data() {
    return {
      imgUrl:'',
      elForm: false,
      idFrom: false,
      resetBtn:false,
      student: {
        id: "",
        name: "",
        sex: "",
        age: "",
        school: "",
        specialty: "",
        currentaddress: "",
        nativeplace: "",
        phone: "",
        email: "",
        picture: ""
      },
    };
  },
  components: {
    headTop,
  },
  created() {
    this.init();
  },
  watch: {
    $route(to, from) {
      // 路由变化的方式，路由发生变化，方法就会执行
      this.init();
    },
  },
  methods: {
    handleAvatarSuccess(res, file) {
      this.imgUrl = URL.createObjectURL(file.raw);
      this.imgUrl = res.data.url;
      this.student.picture = this.imgUrl;
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpg";
      const isPng = file.type === "image/png";
      const isJpeg = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isJPG && !isPng && !isJpeg) {
        this.$message.error('上传头像图片只能是 jpg 或 png 格式!');
        return false;
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
        return false;
      }
      console.log('####################');
      return true;
    },
    init() {
      // 判断请求路径中是否有 id 值
      if (this.$route.params && this.$route.params.id) {
        // 修改操作
        // 1、从路径中获取 id 值
        const id = this.$route.params.id;
        // 2、根据学生 ID 查询学生信息
        this.getStudentInfo(id);
        this.elForm = false;
        // 3、禁用表单项（学生ID）
        this.idFrom = true;
      } else {
        //学生添加
        // 请求路径中 没有id值，做学生添加操作
        // 清空表单
        this.student = {};
        this.imgUrl = '',
        this.elForm = false;
        this.idFrom = false;
      }
    },
    checkStudentId() {
      if (!(this.$route.params && this.$route.params.id)) {
        axios.get(`http://localhost:9000/main/student/selectStudentById/${this.student.id}`).then(res => {
          let code = res.data.code;
          if (code == 200) {
            this.$message({
              message: '警告哦，该学号已被注册！',
              type: 'warning'
            });
          }
        })
      }
    },
    // 根据学号查询学生信息（修改之前的数据回显）
    getStudentInfo(id) {
      axios.get(`http://localhost:9000/main/student/selectStudentById/${id}`).then(res => {
        this.student = res.data.data.student;
        this.imgUrl = res.data.data.student.picture;
      })
    },
    saveOrUpdate() {
      if (this.$route.params && this.$route.params.id) {
        this.resetBtn = true;
        this.updateStudent();
      } else {
        this.resetBtn = false;
        this.addStudent();
      }
    },
    // 修改学生信息
    updateStudent() {
      axios.put('http://localhost:9000/main/student/updateStudentById', this.student).then(res => {
        let code = res.data.code;
        if (code == 200) {
          this.$message({
            message: '恭喜你，修改学生信息成功！',
            type: 'success'
          });
        } else {
          this.$message.error('修改学生失败！');
        }
        this.$router.push('/studentList');
      })
    },

    // 添加学生
    addStudent() {
      axios.post('http://localhost:9000/main/student/addStudent', this.student).then(res => {
        let code = res.data.code;
        if (code == 200) {
          this.$message({
            message: '恭喜你，添加学生成功！',
            type: 'success'
          });
        } else {
          this.$message.error('添加学生失败，该学号已存在！');
        }
        this.$router.push('/studentList');
      })
    },

    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
  },
};
</script>
<style>
.box {
  width: 600px;
  padding: 15px 0;
  margin: 20px auto;
  box-shadow: 0 5px 12px 0 rgba(0, 0, 0, 0.2);
}

.box h3 {
  width: 600px;
  text-align: center;
  margin: 20px 0 30px;
}

.demo-student {
  margin-top: 20px;
  /* margin-left: 100px; */
}

.demo-student .el-form-item {
  width: 500px;
}

.buton {
  width: 600px;
  text-align: center;
}

.i1 {
  width: 150px;
}

.i2 {
  width: 300px;
}

.i3 {
  width: 400px;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>